<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="奖品名称" prop="giftName">
        <el-input
          v-model="queryParams.giftName"
          placeholder="请输入赠品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺编号" prop="shopId">
        <el-input
          v-model="queryParams.shopId"
          placeholder="请输入店铺编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="奖品类型" prop="giftType">
        <el-select v-model="queryParams.giftType" placeholder="请选择奖品类型" clearable size="small">
          <el-option label="普通奖品" value="10" />
          <el-option label="特殊奖品" value="20"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:gift:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:gift:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:gift:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:gift:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="giftList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="giftId"/>
      <el-table-column label="奖品名称" align="center" prop="giftName" />
      <el-table-column label="奖品图片" align="center" prop="giftImg">
        <template slot-scope="{row}">
          <el-image
            class="classify-image"
            :src="row.giftImg"
            style="height: 70px;"
            :preview-src-list="[row.giftImg]"
            fit="contain"
            lazy
          >
            <div slot="error">
              <i class="el-icon-document"/>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="店铺编号" align="center" prop="shopId" />
      <el-table-column label="奖品库存" align="center" prop="giftNum" />
      <el-table-column label="奖品价值" align="center" prop="giftPrice" />
      <el-table-column label="奖品类型" align="center" prop="giftType" >
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.giftType == 10">普通奖品</el-tag>
          <el-tag type="success" v-if="scope.row.giftType == 20">特殊奖品</el-tag>
          <el-tag type="success" v-if="scope.row.giftType == 30">活动礼品</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="中奖概率" align="center" prop="probability" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:gift:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:gift:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品赠品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="奖品名称" prop="giftName">
          <el-input v-model="form.giftName" placeholder="请输入赠品名称" />
        </el-form-item>
        <el-form-item label="奖品图片" prop="giftImg">
          <el-upload
            :action="commonUploadApi"
            :accept="'.png,.jpg'"
            :file-list="fileList"
            :headers="headers"
            :before-remove="handleBeforeRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :limit="1"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="奖品库存" prop="giftNum">
          <el-input v-model="form.giftNum" placeholder="请输入奖品个数" />
        </el-form-item>
        <el-form-item label="奖品价值" prop="giftPrice">
          <el-input v-model="form.giftPrice" placeholder="请输入奖品价值" />
        </el-form-item>
        <el-form-item label="奖品类型">
          <el-select v-model="form.giftType" placeholder="请选择奖品类型">
            <el-option label="普通奖品"  value="10" />
            <el-option label="特殊奖品" value="20"/>
            <el-option label="活动礼品" value="30"/>
          </el-select>
        </el-form-item>
        <el-form-item label="中奖概率" prop="giftRate">
          <el-input v-model="form.giftRate" placeholder="请输入中奖概率" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listGift, getGift, delGift, addGift, updateGift, exportGift} from "@/api/system/gift";
  import {mapGetters} from "vuex";
  import { getToken } from "@/utils/auth";

  export default {
    name: "Gift",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 商品赠品表格数据
        giftList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsId: undefined,
          giftName: undefined,
          giftImg: undefined,
          shopId: undefined,
          giftNum: undefined
        },
        // 表单参数
        form: {},
        fileList: [],
        passGoodsId: undefined,
        headers: { Authorization: "Bearer " + getToken() },
        // 表单校验
        rules: {
          giftName: [
            {required: true, message: "奖品名称不能为空", trigger: "blur"}
          ],
          giftImg: [
            {required: true, message: "奖品图片不能为空", trigger: "blur"}
          ],
          giftPrice: [
            {required: false}
          ],
          giftType: [
            {required: true, message: "奖品类型不能为空", trigger: "blur"}
          ],
          giftRate: [
            {required: true, message: "奖品中奖率不能为空", trigger: "blur"}
          ]
        }
      };
    },
    computed: {
      ...mapGetters([
        'commonUploadApi'
      ])
    },
    created() {
      this.passGoodsId = this.$route.query && this.$route.query.id;
      this.getList();
    },
    methods: {
      /** 查询商品赠品列表 */
      getList() {
        this.loading = true;
        this.queryParams.goodsId=this.passGoodsId;
        listGift(this.queryParams).then(response => {
          this.giftList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          giftId: undefined,
          goodsId: undefined,
          giftName: undefined,
          giftImg: undefined,
          shopId: undefined,
          giftNum: '1'
        };
        this.fileList = [];
        this.resetForm("form");
      },
      handleSuccess(response, file, fileList){
        this.form.giftImg = response.url;
      },
      // 监听上传失败
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message);
        this.msgError(msg.message);
      },
      handleBeforeRemove(file, fileList) {
        this.form.giftImg = null;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.giftId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加奖品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const giftId = row.giftId || this.ids
        getGift(giftId).then(response => {
          this.form = response.data;
          this.fileList = [{url:response.data.giftImg}];
          this.open = true;
          this.title = "修改奖品";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.giftId != undefined) {
              updateGift(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.goodsId=this.passGoodsId;
              addGift(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const giftIds = row.giftId || this.ids;
        this.$confirm('是否确认删除奖品编号为"' + giftIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delGift(giftIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有奖品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportGift(queryParams);
        }).then(response => {
          this.download(response.data);
        }).catch(function () {
        });
      }
    }
  };
</script>
